package com.ljm.boot.helloword.algorithm;


/**
 * 固定窗口时间算法
 * 关注公众号：捡田螺的小男孩
 * @return
 */
public class fixedWindows{

    public  Integer counter = 0;  //统计请求数
    public  long lastAcquireTime =  0L;
    public  Long windowUnit = 1000L ; //假设固定时间窗口是1000ms
    public  Integer threshold = 10; // 窗口阀值是10

    public fixedWindows(Long windowUnit, Integer threshold) {
        this.windowUnit = windowUnit;
        this.threshold = threshold;
        this.counter = 0;
        this.lastAcquireTime = System.currentTimeMillis();
    }

    public synchronized boolean tryAcquire() {
        long currentTime = System.currentTimeMillis();  //获取系统当前时间
        if (currentTime - lastAcquireTime > windowUnit*1000) {  //检查是否在时间窗口内
            counter = 0;  // 计数器清0
            lastAcquireTime = currentTime;  //开启新的时间窗口
        }
        if (counter < threshold) {  // 小于阀值
            counter++;  //计数统计器加1
            return true;
        }
        return false;
    }
}

